<?php
class Post_model extends CI_Model{
	public function getLatestPost($limit = 20, $offset = 0){
		$query = $this->db->query("SELECT SQL_CALC_FOUND_ROWS id, original_url, post_title, post_image, video_code FROM data ORDER BY id DESC LIMIT $offset, $limit");
		$result['data'] = $query->result_array();
		$queryTotal = $this->db->query('SELECT FOUND_ROWS() AS total');
		$row = $queryTotal->row();

		$result['total'] = $row->total;

		return $result;
	}
	public function getPostInfo($postId)
	{
		$query = $this->db->query("SELECT * FROM data WHERE id='$postId'");
		return $query->result_array();
	}
	public function uploadImage($resource)
	{
		$todayFolder = date('Y/m/d/i/');
		if(!file_exists(UPLOAD_PATH.$todayFolder)) mkdir(UPLOAD_PATH.$todayFolder, 0777, true);
		$ext = strtolower(end(explode('.', $resource['name'])));
		if(!in_array($ext, array('png', 'jpg', 'jpeg', 'gif', 'bmp'))) return false;
		$fileName = md5($resource['name']).'.'.$ext;
		try{
			if(move_uploaded_file($resource['tmp_name'], UPLOAD_PATH.$todayFolder.$fileName)){
				generateThumbnail(
					array('path' => $todayFolder, 'name' => $fileName),
					array(
						'150x150' => 'crop',
						'460x460' => 'landscape',
					));
				return $todayFolder.$fileName;
			}
		}
		catch(Exception $ex){
			return false;
		}
		return false;
	}
	public function deletePost($postId)
	{
		try{
			return $this->db->delete('data', array('id' => $postId)); 
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		return false;
	}
}